#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""MySQLPass最小化打包脚本
极简版本，用于将mysqlpass项目打包成一个可独立运行的exe程序
"""

import os
import sys
import subprocess
import shutil

# 确保脚本在正确的目录下运行
script_dir = os.path.dirname(os.path.abspath(__file__))
os.chdir(script_dir)

# 定义项目相关路径和参数
BUILD_NAME = "MySQLPass"
MAIN_SCRIPT = "main.py"


def check_pyinstaller():
    """检查PyInstaller是否已安装"""
    try:
        subprocess.run([sys.executable, "-m", "PyInstaller", "--version"], 
                      check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False


def clean_build_dir():
    """清理之前的构建文件"""
    print("清理之前的构建文件...")
    
    # 清理PyInstaller生成的目录
    for dir_name in ["build", "dist"]:
        dir_path = os.path.join(script_dir, dir_name)
        if os.path.exists(dir_path):
            try:
                shutil.rmtree(dir_path)
            except:
                pass
    
    # 清理spec文件
    for file in os.listdir(script_dir):
        if file.endswith(".spec"):
            try:
                os.remove(os.path.join(script_dir, file))
            except:
                pass


def build_with_pyinstaller():
    """使用PyInstaller打包应用"""
    print("开始打包MySQLPass项目为独立可执行程序...")
    
    # 构建PyInstaller命令参数 - 移除windowed参数以便查看控制台输出
    cmd = [
        sys.executable,
        "-m",
        "PyInstaller",
        "--name", BUILD_NAME,
        "--add-data", f"src{os.pathsep}src",
        "--noupx",  # 禁用UPX压缩
        "--onefile",  # 打包成单个可执行文件
        MAIN_SCRIPT
    ]
    
    # 执行打包命令
    try:
        subprocess.run(cmd, check=True)
        print("打包成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"打包失败: {e}")
        return False
    except Exception as e:
        print(f"打包过程中发生未知错误: {e}")
        return False


def verify_build():
    """验证打包结果"""
    exe_path = os.path.join("dist", f"{BUILD_NAME}.exe")
    if os.path.exists(exe_path):
        print(f"\n=== 打包完成 ===")
        print(f"独立可执行文件已生成: {exe_path}")
        print(f"文件大小: {os.path.getsize(exe_path) / 1024 / 1024:.2f} MB")
        print("\n可以直接运行该exe文件，无需安装Python环境")
        return True
    else:
        print(f"打包失败: 未找到生成的可执行文件 {exe_path}")
        return False


def main():
    """主函数"""
    print("=====================================")
    print("MySQLPass 最小化打包工具")
    print("=====================================")
    
    # 检查PyInstaller是否已安装
    if not check_pyinstaller():
        print("PyInstaller未安装，正在尝试安装...")
        try:
            subprocess.run([sys.executable, "-m", "pip", "install", "pyinstaller"], check=True)
            print("PyInstaller安装成功")
        except:
            print("PyInstaller安装失败，请手动安装: python -m pip install pyinstaller")
            sys.exit(1)
    
    # 清理之前的构建文件
    clean_build_dir()
    
    # 开始打包
    if build_with_pyinstaller():
        # 验证打包结果
        verify_build()
    else:
        print("打包失败，请检查错误信息")
        sys.exit(1)


if __name__ == "__main__":
    main()